/* =================================================================================
File name:       PID_GRANDO.H
    抗积分饱和增量式pid控制器
===================================================================================*/

#ifndef __PID_GRANDO_H__
#define __PID_GRANDO_H__
/*-----------------------------------------------------------------------------
Default initalisation values for the PID objects
-----------------------------------------------------------------------------*/

#define PID_TERM_DEFAULTS \
  {                       \
    0,                    \
        0,                \
        0,                \
        0,                \
        0                 \
  }

#define PID_PARAM_DEFAULTS \
  {                        \
    float(1.0),            \
        float(1.0),        \
        float(0.0),        \
        float(0.0),        \
        float(1.0),        \
        float(1.0),        \
        float(-1.0)        \
  }

#define PID_DATA_DEFAULTS \
  {                       \
    float(0.0),           \
        float(0.0),       \
        float(0.0),       \
        float(0.0),       \
        float(0.0),       \
        float(0.0),       \
        float(0.0),       \
        float(1.0)        \
  }


typedef float _iq;

typedef struct
{
  _iq Ref; // Input: reference set-point
  _iq Fbk; // Input: feedback
  _iq Out; // Output: controller output
  _iq c1;  // Internal: derivative filter coefficient 1
  _iq c2;  // Internal: derivative filter coefficient 2
} PID_TERMINALS;
// note: c1 & c2 placed here to keep structure size under 8 words

typedef struct
{
  _iq Kr;   // Parameter: reference set-point weighting
  _iq Kp;   // Parameter: proportional loop gain
  _iq Ki;   // Parameter: integral gain
  _iq Kd;   // Parameter: derivative gain
  _iq Km;   // Parameter: derivative weighting
  _iq Umax; // Parameter: upper saturation limit
  _iq Umin; // Parameter: lower saturation limit
} PID_PARAMETERS;

typedef struct
{
  _iq up; // Data: proportional term
  _iq ui; // Data: integral term
  _iq ud; // Data: derivative term
  _iq v1; // Data: pre-saturated controller output
  _iq i1; // Data: integrator storage: ui(k-1)
  _iq d1; // Data: differentiator storage: ud(k-1)
  _iq d2; // Data: differentiator storage: d2(k-1)
  _iq w1; // Data: saturation record: [u(k-1) - v(k-1)]
} PID_DATA;

typedef struct
{
  PID_TERMINALS term;
  PID_PARAMETERS param ;
  PID_DATA data;
} pid_grando_t;



pid_grando_t *pid_grando_create(float kp,float ki,float kd,int input_max, int input_min, int out_max, int out_min);

void pid_grando_delete(pid_grando_t *handle);
/*------------------------------------------------------------------------------
  PID Macro Definition PID执行运算
  set_point:目标值
  input:输入值
  out:输出值
  return ：输出值
------------------------------------------------------------------------------*/
float pid_grando_macro(pid_grando_t *handle,float input,float set_point);
void pid_grando_reset(pid_grando_t *handle);
#endif // __PID_H__